package com.jshoperxms.controller.mall.backstage.logistics;

import com.jshoperxms.Response;
import com.jshoperxms.controller.mall.backstage.base.BaseTController;
import com.jshoperxms.controller.mall.backstage.base.IBaseCtrl;
import com.jshoperxms.controller.mall.backstage.base.SearchModel;
import com.jshoperxms.controller.utils.BaseTools;
import com.jshoperxms.controller.utils.DateTools;
import com.jshoperxms.controller.utils.enums.BaseEnums;
import com.jshoperxms.controller.utils.statickey.DefaultValue;
import com.jshoperxms.controller.utils.statickey.SerialKeys;
import com.jshoperxms.controller.utils.statickey.TagWords;
import com.jshoperxms.controller.utils.statickey.WarnWrods;
import com.jshoperxms.entity.BasicRegionT;
import com.jshoperxms.entity.LogisticsBusinessRegionPriceT;
import com.jshoperxms.entity.LogisticsBusinessT;
import com.jshoperxms.service.BasicRegionTService;
import com.jshoperxms.service.LogisticsBusinessRegionPriceTService;
import com.jshoperxms.service.LogisticsBusinessTService;
import org.apache.commons.beanutils.converters.DoubleConverter;
import org.apache.commons.lang3.StringUtils;
import org.hibernate.criterion.Criterion;
import org.hibernate.criterion.MatchMode;
import org.hibernate.criterion.Order;
import org.hibernate.criterion.Restrictions;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author xuhui
 * @version 1.0
 * @time 2016/11/29 17:11
 * @Description
 */
@Controller
@RequestMapping("/mall/logisticsbusiness")
public class LogisticsBusinessTController extends BaseTController implements IBaseCtrl<LogisticsBusinessT> {

    private Map<String,Object> responsedata=new HashMap<>();

    @Resource
    private LogisticsBusinessTService logisticsBusinessTService;

    @Resource
    private BasicRegionTService basicRegionTService;

    @Resource
    private LogisticsBusinessRegionPriceTService logisticsBusinessRegionPriceTService;

    @RequestMapping(value="/save",method= RequestMethod.POST)
    @Override
    public ResponseEntity save(@RequestBody LogisticsBusinessT rq){
        LogisticsBusinessT bean=new LogisticsBusinessT();
        bean.setId(this.serial.Serialid(SerialKeys.LOGISTICSBUSINESS));
        bean.setStatus(rq.getStatus());
        bean.setCreatorid(BaseTools.getAdminCreateId());
        bean.setAddress(rq.getAddress());
        bean.setBankaccount(rq.getBankaccount());
        bean.setBankaddress(rq.getBankaddress());
        bean.setContractor(rq.getContractor());
        bean.setDes(rq.getDes());
        bean.setEmail(rq.getEmail());
        bean.setLogisticsname(rq.getLogisticsname());
        bean.setMobile(rq.getMobile());
        bean.setReceiver(rq.getReceiver());
        bean.setSendrange(rq.getSendrange());
        bean.setTelno(rq.getTelno());
        bean.setUsingway(rq.getUsingway());
        bean.setWebsite(rq.getWebsite());
        bean.setCreatetime(DateTools.getSystemTimeBi());
        bean.setUpdatetime(DateTools.getSystemTimeBi());
        bean.setVersiont(1);
        this.logisticsBusinessTService.save(bean);
        //同时把默认各个地区的运费设置完毕
        saveLogisticsRegionPrice(bean);
        responsedata.put(TagWords.SUCCESS, true);
        responsedata.put(TagWords.MSG,TagWords.OPERATION_SUCCESS);
        return Response.success(responsedata);
    }


    private void saveLogisticsRegionPrice(LogisticsBusinessT rq){
        Criterion criterion=Restrictions.and(Restrictions.eq("type",BaseEnums.BasicRegionType.SHI.getState())).add(Restrictions.ne(TagWords.STATUS, BaseEnums.DataUsingState.DEL.getState()));
        List<BasicRegionT>list=this.basicRegionTService.findByCriteria(BasicRegionT.class, criterion, Order.desc(TagWords.UPDATETIME));
        for(BasicRegionT b:list){
            LogisticsBusinessRegionPriceT bean=new LogisticsBusinessRegionPriceT();
            bean.setId(this.serial.Serialid(SerialKeys.LOGISTICSBUSINESSREGIONPRICE));
            bean.setCreatetime(rq.getCreatetime());
            bean.setCreatorid(rq.getCreatorid());
            bean.setLogisticsid(rq.getId());
            bean.setLogisticsname(rq.getLogisticsname());
            bean.setNormalcost(BigDecimal.valueOf(Double.parseDouble(DefaultValue.DEFAULT_NORMALCOST)));
            bean.setNormalweight(BigDecimal.valueOf(Double.parseDouble(DefaultValue.DEFAULT_NORMALWEIGHT)));
            bean.setOvercost(BigDecimal.valueOf(Double.parseDouble(DefaultValue.DEFAULT_OVERCOST)));
            bean.setOverweight(BigDecimal.valueOf(Double.parseDouble(DefaultValue.DEFAULT_OVERWEIGHT)));
            bean.setRegions(b.getName());
            bean.setStatus(b.getStatus());
            bean.setUpdatetime(rq.getUpdatetime());
            bean.setVersiont(1);
            this.logisticsBusinessRegionPriceTService.save(bean);
        }
    }

    @RequestMapping(value="/find",method= RequestMethod.POST)
    @Override
    public ResponseEntity find(@RequestBody LogisticsBusinessT rq) {
        if(StringUtils.isBlank(rq.getId())){
            responsedata.put(TagWords.SUCCESS,false);
            responsedata.put(TagWords.MSG, WarnWrods.ERROR_PARAMS);
        }else{
            LogisticsBusinessT bean=this.logisticsBusinessTService.findByPK(LogisticsBusinessT.class,rq.getId());
            if(bean!=null){
                responsedata.put(TagWords.BEAN,bean);
                responsedata.put(TagWords.SUCCESS,true);
                responsedata.put(TagWords.MSG,TagWords.OPERATION_SUCCESS);
            }
        }
        return Response.success(responsedata);
    }


    @RequestMapping(value="/del",method= RequestMethod.POST)
    @Override
    public ResponseEntity del(@RequestBody  LogisticsBusinessT rq) {
        if(StringUtils.isBlank(rq.getId())){
            responsedata.put(TagWords.SUCCESS,false);
            responsedata.put(TagWords.MSG,WarnWrods.ERROR_PARAMS);
        }else{
            String ids[]=StringUtils.split(rq.getId(),TagWords.SPLITDOT);
            for(String s:ids){
                LogisticsBusinessT bean=this.logisticsBusinessTService.findByPK(LogisticsBusinessT.class,s);
                if(bean!=null){
                    bean.setStatus(BaseEnums.DataUsingState.DEL.getState());
                    bean.setUpdatetime(DateTools.getSystemTimeBi());
                    this.logisticsBusinessTService.update(bean);
                }
                //删除所有物流商的运费价格
                Criterion criterion=Restrictions.eq("logisticsid",s);
                List<LogisticsBusinessRegionPriceT> logisticsBusinessRegionPriceTs=this.logisticsBusinessRegionPriceTService.findByCriteria(LogisticsBusinessRegionPriceT.class,criterion);
                this.logisticsBusinessRegionPriceTService.deleteAll(logisticsBusinessRegionPriceTs);

            }
            responsedata.put(TagWords.SUCCESS,true);
            responsedata.put(TagWords.MSG,TagWords.OPERATION_SUCCESS);
        }
        return Response.success(responsedata);
    }


    @RequestMapping(value="/update",method= RequestMethod.POST)
    @Override
    public ResponseEntity update(@RequestBody LogisticsBusinessT rq) {
        if(StringUtils.isBlank(rq.getId())){
            responsedata.put(TagWords.SUCCESS,false);
            responsedata.put(TagWords.MSG, WarnWrods.ERROR_PARAMS);
        }else{
            LogisticsBusinessT bean=this.logisticsBusinessTService.findByPK(LogisticsBusinessT.class,rq.getId());
            if(bean!=null){
                bean.setStatus(rq.getStatus());
                bean.setAddress(rq.getAddress());
                bean.setBankaccount(rq.getBankaccount());
                bean.setBankaddress(rq.getBankaddress());
                bean.setContractor(rq.getContractor());
                bean.setDes(rq.getDes());
                bean.setEmail(rq.getEmail());
                bean.setLogisticsname(rq.getLogisticsname());
                bean.setMobile(rq.getMobile());
                bean.setReceiver(rq.getReceiver());
                bean.setSendrange(rq.getSendrange());
                bean.setTelno(rq.getTelno());
                bean.setUsingway(rq.getUsingway());
                bean.setWebsite(rq.getWebsite());
                bean.setUpdatetime(DateTools.getSystemTimeBi());
                bean.setVersiont(bean.getVersiont()+1);
                this.logisticsBusinessTService.update(bean);
                responsedata.put(TagWords.SUCCESS, true);
                responsedata.put(TagWords.MSG, TagWords.OPERATION_SUCCESS);
            }
        }
        return Response.success(responsedata);
    }


    @RequestMapping(value="/findAll",method= RequestMethod.POST)
    @Override
    public ResponseEntity findAll() {
        Criterion criterion= Restrictions.eq(TagWords.STATUS, BaseEnums.DataUsingState.USING.getState());
        List<LogisticsBusinessT> list=this.logisticsBusinessTService.findByCriteria(LogisticsBusinessT.class,criterion, Order.desc(TagWords.UPDATETIME));
        responsedata.put(TagWords.BEANLIST,list);
        responsedata.put(TagWords.SUCCESS, true);
        responsedata.put(TagWords.MSG,TagWords.OPERATION_SUCCESS);
        return Response.success(responsedata);
    }

    @RequestMapping(value="/findByPage",method= RequestMethod.POST)
    @Override
    public ResponseEntity findByPage(SearchModel searchModel, @RequestParam("search[value]") String search, @RequestParam("order[0][column]") String ordervalue, @RequestParam("order[0][dir]") String ordertype) {
        findCustomSearch(searchModel,search,ordervalue,ordertype);
        return Response.success(responsedata);
    }

    @Override
    public void findCustomSearch(SearchModel searchModel, String search, String ordervalue, String ordertype) {
        if(searchModel.getIsCustomSearch()==1){
            int currentPage=searchModel.getCalCurrentPage();
            int lineSize = searchModel.getLength();
            Criterion criterion= Restrictions.ne(TagWords.STATUS, BaseEnums.DataUsingState.DEL.getState());
            if(StringUtils.isNotBlank(searchModel.getName())){
                criterion=Restrictions.and(criterion).add(Restrictions.like("content",searchModel.getName(), MatchMode.ANYWHERE));
            }
            if(StringUtils.isNotBlank(search)){
                criterion=Restrictions.and(criterion).add(Restrictions.like("content",search,MatchMode.ANYWHERE));
            }
            int records=this.logisticsBusinessTService.count(LogisticsBusinessT.class,criterion).intValue();
            searchModel.setRecordsTotal(records);
            searchModel.setRecordsFiltered(records);
            responsedata.put(TagWords.RECORDSTOTAL,records);
            responsedata.put(TagWords.RECORDSFILTERED,records);
            List<LogisticsBusinessT> list = this.logisticsBusinessTService.findByCriteriaByPage(
                    LogisticsBusinessT.class, criterion, Order.desc(TagWords.UPDATETIME), currentPage,
                    lineSize);
            this.processPageList(list);

        }else{
            if(StringUtils.isNotBlank(search)){
                filterSearch(searchModel,search);
            }else{
                findDefaultAll(searchModel,ordervalue,ordertype);
            }
        }
    }

    @Override
    public void filterSearch(SearchModel searchModel, String search) {
        int currentPage=searchModel.getCalCurrentPage();
        int lineSize = searchModel.getLength();
        Criterion criterion=Restrictions.ne(TagWords.STATUS, BaseEnums.DataUsingState.DEL.getState());
        criterion=Restrictions.and(criterion).add(Restrictions.like("content",search,MatchMode.ANYWHERE));
        int records=this.logisticsBusinessTService.count(LogisticsBusinessT.class,criterion).intValue();
        searchModel.setRecordsTotal(records);
        searchModel.setRecordsFiltered(records);
        responsedata.put(TagWords.RECORDSTOTAL,records);
        responsedata.put(TagWords.RECORDSFILTERED,records);
        List<LogisticsBusinessT> list = this.logisticsBusinessTService.findByCriteriaByPage(
                LogisticsBusinessT.class, criterion,Order.desc(TagWords.UPDATETIME), currentPage,
                lineSize);
        this.processPageList(list);
    }

    @Override
    public void findDefaultAll(SearchModel searchModel, String ordervalue, String ordertype) {
        int currentPage=searchModel.getCalCurrentPage();
        int lineSize = searchModel.getLength();
        Criterion criterion=Restrictions.ne(TagWords.STATUS, BaseEnums.DataUsingState.DEL.getState());
        int records=this.logisticsBusinessTService.count(LogisticsBusinessT.class,criterion).intValue();
        searchModel.setRecordsFiltered(records);
        searchModel.setRecordsTotal(records);
        responsedata.put(TagWords.RECORDSTOTAL,records);
        responsedata.put(TagWords.RECORDSFILTERED,records);
        Order order= BaseTools.orderByParam(TagWords.UPDATETIME,ordervalue,ordertype);
        List<LogisticsBusinessT> list = this.logisticsBusinessTService.findByCriteriaByPage(
                LogisticsBusinessT.class, criterion,order, currentPage,
                lineSize);
        this.processPageList(list);
    }

    @Override
    public void processPageList(List<LogisticsBusinessT> list) {
        List<Map<String,Object>>data=new ArrayList<>();
        for(LogisticsBusinessT bean:list){
            Map<String,Object>cellMap=new HashMap<>();
            cellMap.put("id",bean.getId());
            cellMap.put("logisticsname",bean.getLogisticsname());
            cellMap.put("telno",bean.getTelno());
            cellMap.put("website",bean.getWebsite());
            cellMap.put("status", BaseEnums.DataUsingState.getName(bean.getStatus()));
            cellMap.put("updatetime",DateTools.formateLongDateToString(bean.getUpdatetime().longValue()));
            cellMap.put("version", bean.getVersiont());
            data.add(cellMap);
        }
        responsedata.put(TagWords.DATA,data);
    }

    @Override
    public boolean checkDuplicates(String str) {
        return false;
    }
}
